﻿using Bricks.Business.Service;
using Bricks.Component.Utils.Const;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Bricks.Component.Utils.Extensions;
using Bricks.Site.Models;
using System.Text;
using Bricks.Business.Service.CommonSupport;
using Bricks.Component.Utils;
using Bricks.Site.Web.CommonUtils;
using System.Xml;
using Bricks.Business.Models.ScheduleManagement;

namespace Bricks.Site.Web.Controllers
{
    [Export]
    public class EngineeringImageScheduleController : BaseController
    {
        #region 属性
        [Import]
        public IFlowNodeService FlowNodeService { get; set; }
        [Import]
        public IBaklogTaskService BaklogTaskService { get; set; }
        [Import]
        public IProcessedTaskService ProcessedTaskService { get; set; }
        [Import]
        public IFlowUtilsService FlowUtilsService { get; set; }
        [Import]
        public IEngineeringImageScheduleService EngineeringImageScheduleService { get; set; }
        #endregion

        #region 主界面加载
        public ActionResult EngineeringImageScheduleList()
        {
            ContractFilterView contractFilterView = new ContractFilterView();
            contractFilterView.UserType = "1";
            ViewBag.ToolBarInfo = CommonUtils.ScheduleManagementUtils.ConstructToolsAndSetView(contractFilterView, User.Identity.Name, base.GetUserMenuActions(), "EngineeringImageScheduleList");
            return View(contractFilterView);
        }

        public ActionResult GetEngineeringImageScheduleList(string projectID, string contractType, string contractID)
        {
            Guid guidProjectID = string.IsNullOrEmpty(projectID) ? GuidHelper.NewGuid() : projectID.ToGuid();
            Guid guidContractID = string.IsNullOrEmpty(contractID) ? GuidHelper.NewGuid() : contractID.ToGuid();
            List<EngineeringImageScheduleView> lstView = EngineeringImageScheduleService.GetEngineeringImageScheduleList(guidProjectID, contractType, guidContractID);
            SetProcedureMonitor(lstView);
            return Json(lstView, JsonRequestBehavior.AllowGet);
        }

        private void SetProcedureMonitor(List<EngineeringImageScheduleView> lstView)
        {
            foreach (EngineeringImageScheduleView view in lstView)
            {
                string procedureMonitor = string.Empty;
                if (view.HandleState == "0")
                {
                    List<BaklogTaskView> lstBaklogTaskView = BaklogTaskService.GetBaklogTaskByRecordID(view.ID.ToString());
                    if (lstBaklogTaskView.Count == 1)
                    {
                        string nodeName = FlowNodeService.GetFlowNodeByNodeCode(view.FlowCode, true, "").NodeName;
                        string realName = lstBaklogTaskView[0].CurrentProcessPerson;
                        var userInfo = UserInfoService.GetUserInfoByName(lstBaklogTaskView[0].CurrentProcessPerson);
                        if (userInfo != null && !string.IsNullOrEmpty(userInfo.RealName))
                        {
                            realName = userInfo.RealName;
                        }
                        procedureMonitor = "由【" + nodeName + "】【" + realName + "】申请";
                    }
                }
                else if (view.HandleState == "2" || view.HandleState == "3")
                {
                    List<ProcessedTaskView> lstProcessedTaskView = ProcessedTaskService.GetProcessedTaskListByHandleState(view.ID.ToString(), view.HandleState);
                    if (lstProcessedTaskView.Count == 1)
                    {
                        string nodeName = lstProcessedTaskView[0].CurrentProcessNodeName;
                        string realName = lstProcessedTaskView[0].CurrentProcessPerson;
                        var userInfo = UserInfoService.GetUserInfoByName(lstProcessedTaskView[0].CurrentProcessPerson);
                        if (userInfo != null)
                        {
                            realName = userInfo.RealName;
                        }
                        if (view.HandleState == "2")
                        {
                            procedureMonitor = "已由【" + nodeName + "】【" + realName + "】审批完成";
                        }
                        else
                        {
                            procedureMonitor = "已由【" + nodeName + "】【" + realName + "】终止";
                        }
                    }
                }
                else
                {
                    List<BaklogTaskView> lstBaklogTaskView = BaklogTaskService.GetBaklogTaskByRecordID(view.ID.ToString());
                    if (lstBaklogTaskView.Count > 0)
                    {
                        string nodeName = FlowNodeService.GetFlowNodeByNodeCode(view.FlowCode, false, lstBaklogTaskView[0].CurrentFlowNodeCode).NodeName;
                        string realName = string.Empty;
                        foreach (BaklogTaskView baklogTaskView in lstBaklogTaskView)
                        {
                            string userName = baklogTaskView.CurrentProcessPerson;
                            var userInfo = UserInfoService.GetUserInfoByName(userName);
                            if (userInfo != null && !string.IsNullOrEmpty(userInfo.RealName))
                            {
                                userName = userInfo.RealName;
                            }
                            realName += userName + ",";
                        }
                        if (!string.IsNullOrEmpty(realName))
                        {
                            realName = realName.Trim(',');
                        }
                        procedureMonitor = "正在等待【" + nodeName + "】【" + realName + "】审批";
                    }
                }
                view.ProcedureMonitor = procedureMonitor;
            }
        }

        public ActionResult GetEngineeringImageScheduleDetailList(string projectID, string contractType, string contractID, string year, string month, string pid)
        {
            Guid guidProjectID = projectID.ToGuid();
            Guid guidContractID = contractID.ToGuid();
            Guid guidPID = pid.ToGuid();
            return Json(EngineeringImageScheduleService.GetEngineeringImageScheduleDetailList(guidProjectID, contractType, guidContractID, year, month, guidPID), JsonRequestBehavior.AllowGet);
        }
        #endregion

        public ActionResult Delete(string engineeringImageScheduleID)
        {
            Guid guidEngineeringImageScheduleID = engineeringImageScheduleID.ToGuid();
            var result = EngineeringImageScheduleService.Delete(guidEngineeringImageScheduleID);
            if (result.ResultType == OperationResultType.Success)
                return Content(OperationResultType.Success.ToString());
            return Content(result.Message);
        }

        #region 单据界面加载
        public ActionResult EngineeringImageSchedule(string sourceType, string processType, string sourceID, string associatedNodeCode, string lastUpdateUserDepartment, string lastUpdateUser, string engineeringImageScheduleID, string projectID, string contractType, string contractID)
        {
            EngineeringImageScheduleView view = null;
            string processdOrCirculatedNodeCode = string.Empty;
            string processdOrCirculatedUserDepartment = string.Empty;
            if (sourceType == "1")
            {
                string flowCode = "EngineeringImageSchedule";
                string nodeCode = FlowNodeService.GetFlowNodeByNodeCode(flowCode, true, "").NodeCode;
                view = new EngineeringImageScheduleView();
                view.ID = Guid.NewGuid();
                view.FlowCode = flowCode;
                view.ProjectID = projectID.ToGuid();
                view.ContractType = contractType;
                view.ContractID = contractID.ToGuid();
                view.Year = "2012";
                view.Month = "1";
                view.RequestPerson = User.Identity.Name;
                view.RequestDate = DateTime.Now;
                view.HandleState = "0";
                view.AssociatedNodeCode = nodeCode;
                view.LastUpdateUserDepartment = lastUpdateUserDepartment;
                view.LastUpdateUser = User.Identity.Name;
                processdOrCirculatedNodeCode = view.AssociatedNodeCode;
                processdOrCirculatedUserDepartment = lastUpdateUserDepartment;
            }
            else
            {
                view = EngineeringImageScheduleService.GetEngineeringImageScheduleByID(engineeringImageScheduleID.ToGuid());
            }

            if (sourceType == "2" && processType == "1")
            {
                view.AssociatedNodeCode = associatedNodeCode;
                view.LastUpdateUserDepartment = lastUpdateUserDepartment;
                view.LastUpdateUser = lastUpdateUser;
            }

            if (sourceType == "2" || (sourceType == "3" && (processType == "1" || processType == "4" || processType == "5")))
            {
                processdOrCirculatedNodeCode = associatedNodeCode;
                processdOrCirculatedUserDepartment = lastUpdateUserDepartment;
            }
            view.EngineeringImageScheduleDetailListJson = "";
            view.SourceType = sourceType;
            view.ProcessType = processType;
            view.SourceID = sourceID;
            view.ProcessdOrCirculatedNodeCode = processdOrCirculatedNodeCode;
            view.ProcessdOrCirculatedUserDepartment = processdOrCirculatedUserDepartment;
            ConstructTools(view);
            return View(view);
        }
        #endregion

        #region 根据功能权限和业务权限构造工具栏菜单按钮
        private void ConstructTools(EngineeringImageScheduleView view)
        {
            List<UIFunctionView> menuActions = base.GetUserMenuActions();
            StringBuilder sb = new StringBuilder();

            //主界面列表单据双击或单击超链接，只能查看
            if (view.SourceType == "0")
            {
                SetAllDisabled(menuActions, sb);
            }
            //主界面列表新增按钮,初始化只能保存
            else if (view.SourceType == "1")
            {
                SetOneButtonEnabled(menuActions, sb, "Save");
            }
            #region 待办列表
            else if (view.SourceType == "2")
            {
                //类型为待办
                if (view.ProcessType == "1")
                {
                    foreach (UIFunctionView item in menuActions)
                    {
                        string disabled = "";
                        if (item.ActionCode == "Withdraw" || item.ActionCode == "Receipt" || item.ActionCode == "Reminders")
                        {
                            disabled = "disabled='false'";
                        }
                        else if (item.ActionCode == "Back")
                        {
                            FlowNodeView flowNodeView = FlowNodeService.GetFlowNodeByNodeCode(view.FlowCode, false, view.AssociatedNodeCode);
                            if (flowNodeView.NodeType == 1)
                            {
                                disabled = "disabled='false'";
                            }
                        }
                        else if (item.ActionCode == "Cancel")
                        {
                            FlowNodeView flowNodeView = FlowNodeService.GetFlowNodeByNodeCode(view.FlowCode, false, view.AssociatedNodeCode);
                            if (flowNodeView.NodeLevel > 1 || flowNodeView.NodeType == 1)
                            {
                                disabled = "disabled='false'";
                            }
                        }
                        sb.Append(ToolButton(item, disabled));
                    }
                }
                //类型为传阅
                else
                {
                    foreach (UIFunctionView item in menuActions)
                    {
                        string disabled = "disabled='false'";
                        if (item.ActionCode == "Circulated" || item.ActionCode == "Receipt")
                        {
                            disabled = "";
                        }
                        sb.Append(ToolButton(item, disabled));
                    }
                }
            }
            #endregion

            #region 已办列表
            else if (view.SourceType == "3")
            {
                //流转已办
                if (view.ProcessType == "1")
                {
                    foreach (UIFunctionView item in menuActions)
                    {
                        string disabled = "disabled='false'";
                        if (view.HandleState != "2" && view.HandleState != "3")
                        {
                            if (item.ActionCode == "Withdraw")
                            {
                                //获取撤回到的节点信息
                                FlowNodeView flowNodeView = FlowNodeService.GetFlowNodeByNodeCode(view.FlowCode, false, view.ProcessdOrCirculatedNodeCode);
                                List<FlowNodeView> lstCirculationNode = new List<FlowNodeView>();
                                Dictionary<string, List<FlowNodeView>> dicConditionAndCirculationNode = new Dictionary<string, List<FlowNodeView>>();
                                bool isCanWithdraw = CanWithdraw(flowNodeView, view, lstCirculationNode, dicConditionAndCirculationNode);
                                if (isCanWithdraw)
                                {
                                    disabled = "";
                                }
                            }
                            else if (item.ActionCode == "Circulated" || item.ActionCode == "Reminders")
                            {
                                disabled = "";
                            }
                        }
                        sb.Append(ToolButton(item, disabled));
                    }
                }
                //回退已办、终止已办
                else if (view.ProcessType == "2" || view.ProcessType == "3" || view.ProcessType == "6")
                {
                    SetAllDisabled(menuActions, sb);
                }
                //本人传阅或者已阅
                else
                {
                    SetOneButtonEnabled(menuActions, sb, "Circulated");
                }
            }
            #endregion

            //流程消息
            else if (view.SourceType == "4")
            {
                SetAllDisabled(menuActions, sb);
            }

            ViewBag.ToolBarInfo = sb.ToString();
        }

        private void SetAllDisabled(List<UIFunctionView> menuActions, StringBuilder sb)
        {
            foreach (UIFunctionView item in menuActions)
            {
                sb.Append(ToolButton(item, "disabled='false'"));
            }
        }

        private void SetOneButtonEnabled(List<UIFunctionView> menuActions, StringBuilder sb, string code)
        {
            foreach (UIFunctionView item in menuActions)
            {
                string disabled = "disabled='false'";
                if (item.ActionCode == code)
                {
                    disabled = "";
                }
                sb.Append(ToolButton(item, disabled));
            }
        }

        public string ToolButton(UIFunctionView item, string disabled = "")
        {
            return "<a href='javascript:void(0)' id='btn" + item.ActionCode + "' class='easyui-linkbutton' onclick='" + item.MenuCode + "." + item.ActionCode + "()' data-options='plain:true,iconCls:\"" + item.Icon + "\"'" + disabled + ">" + item.ActionName + "</a>";
        }
        #endregion

        #region 判断是否有撤回权限
        /// <summary>
        /// 判断是否有撤回权限
        /// </summary>
        /// <param name="flowNodeView">撤回到的节点信息</param>
        /// <param name="recordID">单据ID</param>
        /// <param name="lstCirculationNode">根据withdrawNodeCode获取要流转的节点列表</param>
        /// <param name="dicConditionAndCirculationNode">根据withdrawNodeCode获取条件节点流转的节点字典</param>
        /// <returns></returns>
        private bool CanWithdraw(FlowNodeView flowNodeView, EngineeringImageScheduleView view, List<FlowNodeView> lstCirculationNode, Dictionary<string, List<FlowNodeView>> dicConditionAndCirculationNode)
        {
            //分析撤回到的节点的XML里面的circulationCell，获取节点Code数组
            string[] arrFlowNodeCode = GetNodeCodeByXMLForCirculation(flowNodeView.NodeXML, view.ID.ToString());

            //根据第一次获取到的节点数组，获取所有的中间经过的条件节点和流转节点
            foreach (string flowNodeCode in arrFlowNodeCode)
            {
                List<FlowNodeView> lstConditionAndCirculationNode = new List<FlowNodeView>();
                GetConditionAndCirculationNode(view.FlowCode, flowNodeCode, view.ID.ToString(), view.ProcessdOrCirculatedUserDepartment, lstCirculationNode, lstConditionAndCirculationNode);
                dicConditionAndCirculationNode.Add(flowNodeCode, lstConditionAndCirculationNode);
            }

            //判断是否流转的节点对应的每个人在待办里面都能找到
            List<BaklogTaskView> lstBaklogTask = BaklogTaskService.GetBaklogTaskByRecordID(view.ID.ToString());
            foreach (FlowNodeView circulationNode in lstCirculationNode)
            {
                string[] processDepartmentAndPersonArr = circulationNode.DefaultProcessPerson.Split(',');
                foreach (string processDepartmentAndPerson in processDepartmentAndPersonArr)
                {
                    string[] subProcessDepartmentAndPersonArr = processDepartmentAndPerson.Split('|');

                    //是否找不到待办
                    BaklogTaskView existsBaklogTaskView = lstBaklogTask.SingleOrDefault(b => b.CurrentFlowNodeCode == circulationNode.NodeCode && b.CurrentProcessPerson == subProcessDepartmentAndPersonArr[1]);
                    if (existsBaklogTaskView == null)
                    {
                        return false;
                    }

                    //是否点击了保存按钮
                    if (view.SaveState == "1")
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 根据节点的XML获取流转节点Code
        /// </summary>
        /// <param name="nodeXML">节点的XML</param>
        /// <param name="recordID">单据ID</param>
        /// <returns></returns>
        private string[] GetNodeCodeByXMLForCirculation(string nodeXML, string recordID)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(nodeXML);
            XmlNodeList nodeList = doc.SelectNodes("NodeXML/circulationCell");
            string getType = nodeList[0].SelectSingleNode("getType").InnerText;
            string processNodeCode = string.Empty;
            if (getType.ToLower() == "value")
            {
                processNodeCode = nodeList[0].SelectSingleNode("cellsName").InnerText;
            }
            else
            {
                string functionName = nodeList[0].SelectSingleNode("functionName").InnerText;
                Hashtable para = new Hashtable();
                para.Add("IsGetBusinessData", true);
                para.Add("RecordID", recordID);
                XmlNode paraNode = nodeList[0].SelectSingleNode("functionParam");
                if (paraNode != null)
                {
                    para.Add(paraNode.Name, paraNode.InnerText);
                }
                processNodeCode = FlowUtilsService.ExecuteCommand(functionName, para) as string;
            }
            return processNodeCode.Split(',');
        }

        /// <summary>
        /// 获取所有的中间经过的条件节点和流转节点
        /// </summary>
        /// <param name="flowCode">流程编码</param>
        /// <param name="flowNodeCode">流程节点编码</param>
        /// <param name="recordID">单据ID</param>
        /// <param name="dicCirculationNode">记录流转节点的字典</param>
        /// <param name="lstConditionAndCirculationNode">记录条件节点和流转节点的List</param>
        private void GetConditionAndCirculationNode(string flowCode, string flowNodeCode, string recordID, string processUserDepartment, List<FlowNodeView> lstCirculationNode, List<FlowNodeView> lstConditionAndCirculationNode)
        {
            FlowNodeView flowNodeView = FlowNodeService.GetFlowNodeByNodeCode(flowCode, false, flowNodeCode);
            lstConditionAndCirculationNode.Add(flowNodeView);
            if (flowNodeView.NodeType == 2)
            {
                //如果是条件节点，获取条件节点的XML数据并解析，递归调用
                string[] arrFlowNodeCode = GetNodeCodeByXMLForCirculation(flowNodeView.NodeXML, recordID);
                foreach (string nextNodeCode in arrFlowNodeCode)
                {
                    GetConditionAndCirculationNode(flowCode, nextNodeCode, recordID, processUserDepartment, lstCirculationNode, lstConditionAndCirculationNode);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(flowNodeView.NodeXML))
                {
                    flowNodeView.DefaultProcessPerson = GetDefaultProcessPerson(flowNodeView.NodeXML, processUserDepartment);
                }
                lstCirculationNode.Add(flowNodeView);
            }
        }

        /// <summary>
        /// 获取缺省处理人和部门
        /// </summary>
        /// <param name="docPerson">节点xml文档</param>
        /// <param name="recordID">单据ID</param>
        /// <returns></returns>
        private string GetDefaultProcessPerson(string nodeXML, string processUserDepartment)
        {
            string defaultProcessPerson = string.Empty;
            XmlDocument docPerson = new XmlDocument();
            docPerson.LoadXml(nodeXML);
            XmlNode personNode = docPerson.SelectSingleNode("NodeXML/defaultProcessPerson");
            if (personNode != null)
            {
                string processPersonGetType = personNode.SelectSingleNode("getType").InnerText;
                if (processPersonGetType == "value")
                {
                    defaultProcessPerson = personNode.SelectSingleNode("presonList").InnerText;
                }
                else
                {
                    string functionName = personNode.SelectSingleNode("functionName").InnerText;
                    Hashtable para = new Hashtable();
                    para.Add("OrgCode", processUserDepartment);
                    XmlNode paraNode = personNode.SelectSingleNode("functionParam");
                    if (paraNode != null)
                    {
                        para.Add(paraNode.Name, paraNode.InnerText);
                    }
                    defaultProcessPerson = FlowUtilsService.ExecuteCommand(functionName, para) as string;
                }
            }
            return defaultProcessPerson;
        }
        #endregion

        #region 保存
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Save(EngineeringImageScheduleView model)
        {
            try
            {
                string message = string.Empty;
                if (ValidateYearAndMonth(model, ref message) && ValidateInputAmount(model, ref message))
                {
                    if (model.SourceType == "1")
                    {
                        EngineeringImageScheduleView view = EngineeringImageScheduleService.GetEngineeringImageScheduleByID(model.ID);
                        if (view == null)
                        {
                            List<BaklogTaskView> addList = new List<BaklogTaskView>();
                            addList.Add(new BaklogTaskView()
                            {
                                ID = GuidHelper.NewGuid(),
                                RecordID = model.ID.ToString(),
                                TaskType = model.FlowCode,
                                RequestDate = model.RequestDate,
                                CurrentFlowNodeCode = model.AssociatedNodeCode,
                                CurrentProcessPersonDepartment = model.LastUpdateUserDepartment,
                                CurrentProcessPerson = model.LastUpdateUser,
                                NodeLevel = 1
                            });
                            BaklogTaskService.AddBaklogTask(addList);
                        }
                    }
                    model.LastUpdateTime = DateTime.Now;
                    model.SaveState = "1";

                    List<EngineeringImageScheduleDetailsView> saveList = new List<EngineeringImageScheduleDetailsView>();
                    if (!string.IsNullOrEmpty(model.EngineeringImageScheduleDetailListJson as string))
                    {
                        string engineeringImageScheduleDetailListJsonNew = "{\"lstEngineeringImageScheduleDetailView\":" + model.EngineeringImageScheduleDetailListJson + "}";
                        XmlNode nodeList = XMLJsonUtils.JsonToXml(engineeringImageScheduleDetailListJsonNew).SelectSingleNode("root/lstEngineeringImageScheduleDetailView");
                        foreach (XmlNode childNode in nodeList.ChildNodes)
                        {
                            string totalDesignMoneyNum = childNode.SelectSingleNode("TotalDesignMoneyNum").InnerText;
                            string cumulativeCompletedMoneyNum = childNode.SelectSingleNode("CumulativeCompletedMoneyNum").InnerText;
                            string currentYearPlanCompletedMoneyNum = childNode.SelectSingleNode("CurrentYearPlanCompletedMoneyNum").InnerText;
                            string currentMonthCompletedMoneyNum = childNode.SelectSingleNode("CurrentMonthCompletedMoneyNum").InnerText;
                            string cumulativeToCurrentMonthCompletedMoneyNum = childNode.SelectSingleNode("CumulativeToCurrentMonthCompletedMoneyNum").InnerText;
                            string remark = childNode.SelectSingleNode("Remark").InnerText;
                            if (!string.IsNullOrEmpty(totalDesignMoneyNum) || !string.IsNullOrEmpty(cumulativeCompletedMoneyNum) || !string.IsNullOrEmpty(currentYearPlanCompletedMoneyNum) || !string.IsNullOrEmpty(currentMonthCompletedMoneyNum) || !string.IsNullOrEmpty(cumulativeToCurrentMonthCompletedMoneyNum) || !string.IsNullOrEmpty(remark))
                            {
                                Guid id = childNode.SelectSingleNode("ID").InnerText.ToGuid();
                                EngineeringImageScheduleDetailsView engineeringImageScheduleDetailsView = saveList.SingleOrDefault(t => t.ID == id);
                                if (engineeringImageScheduleDetailsView == null)
                                {
                                    EngineeringImageScheduleDetailsView add = new EngineeringImageScheduleDetailsView();
                                    add.ID = id;
                                    add.EngineeringImageScheduleID = model.ID;
                                    add.EngineeringImageStatisticsItemID = childNode.SelectSingleNode("EngineeringImageStatisticsItemID").InnerText.ToGuid();
                                    if (!string.IsNullOrEmpty(totalDesignMoneyNum))
                                    {
                                        add.TotalDesignMoneyNum = Convert.ToDouble(totalDesignMoneyNum);
                                    }
                                    if (!string.IsNullOrEmpty(cumulativeCompletedMoneyNum))
                                    {
                                        add.CumulativeCompletedMoneyNum = Convert.ToDouble(cumulativeCompletedMoneyNum);
                                    }
                                    if (!string.IsNullOrEmpty(currentYearPlanCompletedMoneyNum))
                                    {
                                        add.CurrentYearPlanCompletedMoneyNum = Convert.ToDouble(currentYearPlanCompletedMoneyNum);
                                    }
                                    if (!string.IsNullOrEmpty(currentMonthCompletedMoneyNum))
                                    {
                                        add.CurrentMonthCompletedMoneyNum = Convert.ToDouble(currentMonthCompletedMoneyNum);
                                    }
                                    if (!string.IsNullOrEmpty(cumulativeToCurrentMonthCompletedMoneyNum))
                                    {
                                        add.CumulativeToCurrentMonthCompletedMoneyNum = Convert.ToDouble(cumulativeToCurrentMonthCompletedMoneyNum);
                                    }
                                    add.Remark = remark;
                                    saveList.Add(add);
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(totalDesignMoneyNum))
                                    {
                                        engineeringImageScheduleDetailsView.TotalDesignMoneyNum = Convert.ToDouble(totalDesignMoneyNum);
                                    }
                                    if (!string.IsNullOrEmpty(cumulativeCompletedMoneyNum))
                                    {
                                        engineeringImageScheduleDetailsView.CumulativeCompletedMoneyNum = Convert.ToDouble(cumulativeCompletedMoneyNum);
                                    }
                                    if (!string.IsNullOrEmpty(currentYearPlanCompletedMoneyNum))
                                    {
                                        engineeringImageScheduleDetailsView.CurrentYearPlanCompletedMoneyNum = Convert.ToDouble(currentYearPlanCompletedMoneyNum);
                                    }
                                    if (!string.IsNullOrEmpty(currentMonthCompletedMoneyNum))
                                    {
                                        engineeringImageScheduleDetailsView.CurrentMonthCompletedMoneyNum = Convert.ToDouble(currentMonthCompletedMoneyNum);
                                    }
                                    if (!string.IsNullOrEmpty(cumulativeToCurrentMonthCompletedMoneyNum))
                                    {
                                        engineeringImageScheduleDetailsView.CumulativeToCurrentMonthCompletedMoneyNum = Convert.ToDouble(cumulativeToCurrentMonthCompletedMoneyNum);
                                    }
                                    engineeringImageScheduleDetailsView.Remark = remark;
                                }
                            }
                        }
                    }
                    EngineeringImageScheduleService.SaveEngineeringImageSchedule(model, saveList);
                    return Content("保存成功！");
                }
                else
                {
                    return Content(message);
                }

            }
            catch (Exception ex)
            {
                return Content("保存失败：" + ex.Message);
            }
        }

        private bool ValidateYearAndMonth(EngineeringImageScheduleView model, ref string message)
        {
            EngineeringImageScheduleView view = EngineeringImageScheduleService.GetEngineeringImageScheduleByID(model.ID);
            IQueryable<EngineeringImageSchedule> lstEngineeringImageSchedule = EngineeringImageScheduleService.EngineeringImageSchedules.Where(y => y.ProjectID == model.ProjectID && y.ContractType == model.ContractType && y.ContractID == model.ContractID && y.Year == model.Year && y.Month == model.Month);
            if (view == null)
            {
                if (lstEngineeringImageSchedule.Count() > 0)
                {
                    message = "统计周期【" + model.Year + "年" + model.Month + "月】已经存在！";
                    return false;
                }
            }
            else
            {
                if (lstEngineeringImageSchedule.Count() > 1)
                {
                    message = "统计周期【" + model.Year + "年" + model.Month + "月】已经存在！";
                    return false;
                }
            }
            return true;
        }

        private bool ValidateInputAmount(EngineeringImageScheduleView model, ref string message)
        {
            bool isPass = true;
            if (!string.IsNullOrEmpty(model.EngineeringImageScheduleDetailListJson as string))
            {
                string engineeringImageScheduleDetailListJsonNew = "{\"lstEngineeringImageScheduleDetailView\":" + model.EngineeringImageScheduleDetailListJson + "}";
                XmlNode nodeList = XMLJsonUtils.JsonToXml(engineeringImageScheduleDetailListJsonNew).SelectSingleNode("root/lstEngineeringImageScheduleDetailView");
                foreach (XmlNode childNode in nodeList.ChildNodes)
                {
                    string statisticsItemName = childNode.SelectSingleNode("EngineeringImageStatisticsItemName").InnerText;
                    if (!ValidateInputSingleAmount(statisticsItemName, childNode.SelectSingleNode("TotalDesignMoneyNum").InnerText, ref message))
                    {
                        continue;
                    }
                    if (!ValidateInputSingleAmount(statisticsItemName, childNode.SelectSingleNode("CumulativeCompletedMoneyNum").InnerText, ref message))
                    {
                        continue;
                    }
                    if (!ValidateInputSingleAmount(statisticsItemName, childNode.SelectSingleNode("CurrentYearPlanCompletedMoneyNum").InnerText, ref message))
                    {
                        continue;
                    }
                    if (!ValidateInputSingleAmount(statisticsItemName, childNode.SelectSingleNode("CurrentMonthCompletedMoneyNum").InnerText, ref message))
                    {
                        continue;
                    }
                    if (!ValidateInputSingleAmount(statisticsItemName, childNode.SelectSingleNode("CumulativeToCurrentMonthCompletedMoneyNum").InnerText, ref message))
                    {
                        continue;
                    }
                }
            }
            if (!string.IsNullOrEmpty(message))
            {
                isPass = false;
                message = message.Trim(',') + "的金额不是数字！";
            }
            return isPass;
        }

        private bool ValidateInputSingleAmount(string statisticsItemName, string amount, ref string message)
        {
            if (!string.IsNullOrEmpty(amount))
            {
                try
                {
                    decimal value = Convert.ToDecimal(amount);
                }
                catch (Exception ex)
                {
                    message += "【" + statisticsItemName + "】,";
                    return false;
                }
            }
            return true;
        }
        #endregion

        public ActionResult Withdraw(EngineeringImageScheduleView model, string withdrawNodeCode)
        {
            try
            {
                //获取撤回到的节点信息
                FlowNodeView flowNodeView = FlowNodeService.GetFlowNodeByNodeCode(model.FlowCode, false, withdrawNodeCode);
                List<FlowNodeView> lstCirculationNode = new List<FlowNodeView>();
                Dictionary<string, List<FlowNodeView>> dicConditionAndCirculationNode = new Dictionary<string, List<FlowNodeView>>();
                bool isCanWithdraw = CanWithdraw(flowNodeView, model, lstCirculationNode, dicConditionAndCirculationNode);
                if (isCanWithdraw)
                {
                    FlowUtilsService.Withdraw(flowNodeView, model.FlowCode, model.ID.ToString(), model.ProcessdOrCirculatedUserDepartment, model.RequestDate, lstCirculationNode, dicConditionAndCirculationNode);
                    return Content("Success");
                }
                else
                {
                    return Content("已经有人处理，不能撤回！");
                }
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        public ActionResult Cancel(string flowCode, string id)
        {
            try
            {
                FlowUtilsService.Cancel(flowCode, User.Identity.Name, id);
                EngineeringImageScheduleView view = EngineeringImageScheduleService.GetEngineeringImageScheduleByID(id.ToGuid());
                view.HandleState = "3";
                EngineeringImageScheduleService.SaveEngineeringImageSchedule(view, new List<EngineeringImageScheduleDetailsView>(), false);
                return Content("Success");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        public ActionResult Reminders(string flowCode, string id)
        {
            try
            {
                FlowUtilsService.Reminders(id, flowCode, User.Identity.Name);
                return Content("Success");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        public ActionResult GenerateGraph(string flowCode, string id)
        {
            EngineeringImageScheduleView view = EngineeringImageScheduleService.GetEngineeringImageScheduleByID(id.ToGuid());
            string handleState = "";
            if (view != null)
            {
                handleState = view.HandleState;
            }
            WorkFlowView workFlowView = FlowUtilsService.GenerateGraph(flowCode, id, handleState);
            return Json(workFlowView, JsonRequestBehavior.AllowGet);
        }
    }
}
